import { ref, computed, readonly } from 'vue'
import { GameHistory } from '../types/game'
import { Card, CardCombination, PATTERN_NAMES } from '../types/card'

/**
 * 游戏历史记录管理组合式函数
 */
export function useGameHistory() {
  // 响应式数据
  const history = ref<GameHistory[]>([])
  const maxHistorySize = ref<number>(100) // 最大历史记录数量

  /**
   * 添加历史记录
   */
  const addRecord = (record: GameHistory) => {
    try {
      // 添加到历史记录
      history.value.push({
        ...record,
        timestamp: new Date()
      })

      // 如果超过最大数量，删除最旧的记录
      if (maxHistorySize.value > 0 && history.value.length > maxHistorySize.value) {
        history.value = history.value.slice(-maxHistorySize.value)
      }

      console.log('添加历史记录:', {
        player: record.playerName,
        cards: record.cards.map(c => c.display),
        pattern: PATTERN_NAMES[record.combination.type]
      })

    } catch (error) {
      console.error('添加历史记录失败:', error)
      throw error
    }
  }

  /**
   * 批量添加历史记录
   */
  const addRecords = (records: GameHistory[]) => {
    records.forEach(record => addRecord(record))
  }

  /**
   * 清空历史记录
   */
  const clearHistory = () => {
    history.value = []
  }

  /**
   * 删除指定记录
   */
  const removeRecord = (recordId: string) => {
    const index = history.value.findIndex(record => record.id === recordId)
    if (index >= 0) {
      history.value.splice(index, 1)
    }
  }

  /**
   * 获取指定玩家的历史记录
   */
  const getPlayerHistory = (playerId: number): GameHistory[] => {
    return history.value.filter(record => record.playerId === playerId)
  }

  /**
   * 获取指定轮次的历史记录
   */
  const getRoundHistory = (round: number): GameHistory[] => {
    return history.value.filter(record => record.round === round)
  }

  /**
   * 获取最近的历史记录
   */
  const getRecentHistory = (count: number = 10): GameHistory[] => {
    return history.value.slice(-count)
  }

  /**
   * 搜索历史记录
   */
  const searchHistory = (criteria: {
    playerId?: number
    round?: number
    patternType?: number
    startTime?: Date
    endTime?: Date
  }): GameHistory[] => {
    return history.value.filter(record => {
      if (criteria.playerId !== undefined && record.playerId !== criteria.playerId) {
        return false
      }

      if (criteria.round !== undefined && record.round !== criteria.round) {
        return false
      }

      if (criteria.patternType !== undefined && record.combination.type !== criteria.patternType) {
        return false
      }

      if (criteria.startTime && record.timestamp < criteria.startTime) {
        return false
      }

      if (criteria.endTime && record.timestamp > criteria.endTime) {
        return false
      }

      return true
    })
  }

  /**
   * 获取历史统计信息
   */
  const getHistoryStats = computed(() => {
    const stats = {
      totalRecords: history.value.length,
      playerStats: {} as Record<number, {
        playCount: number
        passCount: number
        lastPlay: GameHistory | null
      }>,
      patternStats: {} as Record<number, number>,
      roundStats: {} as Record<number, number>
    }

    history.value.forEach(record => {
      // 玩家统计
      if (!stats.playerStats[record.playerId]) {
        stats.playerStats[record.playerId] = {
          playCount: 0,
          passCount: 0,
          lastPlay: null
        }
      }

      const playerStat = stats.playerStats[record.playerId]
      playerStat.playCount++
      playerStat.lastPlay = record

      if (record.cards.length === 0) {
        playerStat.passCount++
      }

      // 牌型统计
      const patternType = record.combination.type
      stats.patternStats[patternType] = (stats.patternStats[patternType] || 0) + 1

      // 轮次统计
      stats.roundStats[record.round] = (stats.roundStats[record.round] || 0) + 1
    })

    return stats
  })

  /**
   * 获取最后一次出牌记录
   */
  const getLastPlay = computed((): GameHistory | null => {
    return history.value.length > 0 ? history.value[history.value.length - 1] : null
  })

  /**
   * 获取最后一次有效出牌记录（非过牌）
   */
  const getLastValidPlay = computed((): GameHistory | null => {
    for (let i = history.value.length - 1; i >= 0; i--) {
      const record = history.value[i]
      if (record.cards.length > 0) {
        return record
      }
    }
    return null
  })

  /**
   * 检查是否有历史记录
   */
  const hasHistory = computed(() => history.value.length > 0)

  /**
   * 获取当前轮次
   */
  const getCurrentRound = computed(() => {
    if (history.value.length === 0) return 1
    return Math.max(...history.value.map(record => record.round))
  })

  /**
   * 格式化历史记录用于显示
   */
  const formatHistoryForDisplay = computed(() => {
    return history.value.map(record => ({
      id: record.id,
      time: record.timestamp.toLocaleTimeString(),
      player: record.playerName,
      action: record.cards.length === 0 ? '过牌' :
        `${PATTERN_NAMES[record.combination.type]} (${record.cards.map(c => c.display).join(' ')})`,
      round: record.round,
      cardCount: record.cards.length,
      patternName: PATTERN_NAMES[record.combination.type],
      power: record.combination.power
    }))
  })

  /**
   * 导出历史记录
   */
  const exportHistory = (): string => {
    return JSON.stringify(history.value, null, 2)
  }

  /**
   * 导入历史记录
   */
  const importHistory = (data: string) => {
    try {
      const importedHistory = JSON.parse(data) as GameHistory[]

      // 验证数据格式
      if (!Array.isArray(importedHistory)) {
        throw new Error('导入数据格式错误')
      }

      // 转换时间戳
      importedHistory.forEach(record => {
        if (typeof record.timestamp === 'string') {
          record.timestamp = new Date(record.timestamp)
        }
      })

      history.value = importedHistory

    } catch (error) {
      console.error('导入历史记录失败:', error)
      throw error
    }
  }

  /**
   * 设置最大历史记录数量
   */
  const setMaxHistorySize = (size: number) => {
    maxHistorySize.value = size

    // 如果当前记录超过限制，截断到限制数量
    if (size > 0 && history.value.length > size) {
      history.value = history.value.slice(-size)
    }
  }

  return {
    // 状态
    history: readonly(history),
    maxHistorySize: readonly(maxHistorySize),

    // 计算属性
    getHistoryStats,
    getLastPlay,
    getLastValidPlay,
    hasHistory,
    getCurrentRound,
    formatHistoryForDisplay,

    // 方法
    addRecord,
    addRecords,
    clearHistory,
    removeRecord,
    getPlayerHistory,
    getRoundHistory,
    getRecentHistory,
    searchHistory,
    exportHistory,
    importHistory,
    setMaxHistorySize
  }
}